<?php

App::uses('AppController', 'Controller');

/**
 * @property Loyalty $Loyalty Loyalty Model
 * @property LoyaltySubscriber $LoyaltySubscriber Subscriber Model
 * @property LoyaltyVoucher $LoyaltyVoucher Voucher Model
 */
class MessagesController extends AppController {

    public $uses = array('LoyaltySubscriber', 'Loyalty', 'LoyaltyCoupon', 'LoyaltyVoucher', 'Keyword', 'Broadcaster', 'Moderator', 'BroadcasterOutbox', 'BroadcasterModerator','BroadcasterQueue');
    public $components = array('Message');

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('receive', 'subscribe', 'test','process_queue');
    }

    public function receive() {
        $this->autoRender = false;

        /*$sender_no = isset($_SESSION['send_no']) ? $_SESSION['send_no'] : $_REQUEST['send_no'];
        $sms = isset($_SESSION['sms']) ? trim($_SESSION['sms']) : $_REQUEST['sms'];
        $scode = isset($_SESSION['code']) ? $_SESSION['code'] : $_REQUEST['code'];*/

        $sender_no = $_GET['send_no'];
        $sms = $_GET['sms'];
        $scode = $_GET['code'];

        $sdate = gmdate("Y-m-d") . " " . gmdate("H:i:s");

        $response = null;

        if ($sender_no !== '' && $scode !== '') {

            //Break the sms in bits for further usage
            $sms_pieces = explode(" ", $sms);

            if (count($sms_pieces) > 0) {

                if (strtolower($sms_pieces[0]) == "approve" && isset($sms_pieces[1])) {
                    $response = $this->approveMessageForSending($sms_pieces[1], $sender_no);
                    return;
                    
                } else {
                    $response = $this->Loyalty->registerOrRedeem($sms_pieces[0], $sender_no);
                }
                
            }
            else {
                $response = array('message' => "Invalid Message Format Sent.");
            }

            $result = $this->Message->sendSMS($response['message'], $sender_no, $scode);

        } else {
            return "No Sender Number or Short Code Received";
        }
    }

    public function subscribe($loyalty_id, $sender_no) {
        $subscriber = new LoyaltySubscriber();

        $subscriber->set(array(
            'loyalty_id' => $loyalty_id,
            'mobile' => $sender_no
        ));

        return $subscriber->save();
    }


    public function process_queue() {
        $this->autoRender = false;

        $messages = $this->BroadcasterQueue->find('all',array(
            'conditions'=>array('BroadcasterQueue.deleted'=>null),
            'limit'=>20
        ));

        foreach($messages as $message){
            $id = $message['BroadcasterQueue']['id'];
            $number = $message['BroadcasterQueue']['subscriber_no'];
            $msg = $message['BroadcasterQueue']['message'];

            $result = $this->Message->sendSMS($msg, $number, 1471);
            //Update as deleted
            $this->BroadcasterQueue->save(array(
                'id'=>$id,
                'deleted'=>'yes'
            ));
        }

        return;
    }

    public function test() {
        
    }

    /**
     * Approves the specified message by ID for sending
     * 1. Determines if $sender_no is a valid moderator
     * 2. Determines if the moderator found is associated with the keyword for the broadcaster
     * 3. Finds the message and determines if it is pending approval
     * 4. Updates the message with the approver_id and date, and flips the status
     * 5. Sends an SMS to all moderators in the group notifies them that an approval has been done.
     * 
     * @param type $message_id
     * @param type $sender_no
     * @return boolean
     */
    public function approveMessageForSending($message_id, $sender_no) {
        // find moderator by number
        $approver = $this->Moderator->find('first', array(
            'conditions' => array('Moderator.mobile_num1' => $sender_no))
        );

        // if moderator found, find the message to be sent
        if ($approver) {
            $message = $this->BroadcasterOutbox->find('first', array(
                'contain' => array('BroadcasterKeyword'),
                'conditions' => array(
                    'BroadcasterOutbox.id' => $message_id,
                    'BroadcasterOutbox.status' => 'pending')
                )
            );

            // if the message is valid, determine if the moderator can approve the message
            if ($message) {
                
                $canApprove = $this->BroadcasterModerator->find('count', array(
                    'conditions' => array(
                        'BroadcasterModerator.moderator_id' => $approver['Moderator']['id'],
                        'BroadcasterModerator.keyword_id' => $message['BroadcasterKeyword']['keyword_id'])
                    )
                );

                // if moderator can approve message, flag message and notify all moderators of approval
                if ($canApprove) {
                    $response = $this->Broadcaster->approveMessageAndSetupQueue($message_id, $approver['Moderator']['id']);
                    
                    if ($response) {
                        $moderators = $this->BroadcasterModerator->find('all', array(
                            'contain' => array('Moderator'),
                            'conditions' => array('BroadcasterModerator.keyword_id' => $response['BroadcasterKeyword']['keyword_id'])
                            )
                        );

                        foreach ($moderators as $moderator) {
                            $this->Message->sendSMS("Message {$message_id} has been approved by {$approver['Moderator']['firstname']}", 1471, $moderator['Moderator']['mobile_num1']);
                        }

                        return true;
                    }
                }
            }
        }

        return false;
    }

}

?>
